using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace LFromeWork
{
    /// <summary>
    /// 注意，很重要，这里回池用的是 gameObject name 进行的判断
    /// 所以不可以有同名的预制体
    /// </summary>
    public class GameObjectPool : IDisposable
    {
        private Dictionary<string, GameObjectPoolEntity> PoolEntityDic = new Dictionary<string, GameObjectPoolEntity>();

        /// <summary>
        /// 出池子
        /// </summary>
        /// <param name="namePath"></param>
        /// <param name="instanceComplete"></param>
        public GameObject Spawn(string assetFullPath, Transform parent)
        {
            GameObjectPoolEntity poolEntity = null;
            if (!PoolEntityDic.TryGetValue(assetFullPath, out poolEntity))
            {
                poolEntity = new GameObjectPoolEntity();
                PoolEntityDic[assetFullPath] = poolEntity;
            }

            return poolEntity.Spawn(assetFullPath, parent);
        }

        /// <summary>
        /// 回池
        /// </summary>
        /// <param name="namePath"></param>
        /// <param name="instanceComplete"></param>
        public void Despawn(GameObject obj)
        {
            if (obj == null)
                return;
            foreach (var item in PoolEntityDic)
            {
                if (obj.name.Contains(item.Value.GetPrefabName()))
                {
                    item.Value.Despawn(obj);
                    break;
                }
            }
        }

        /// <summary>
        /// 释放对象池
        /// </summary>
        /// <param name="assetFullPath"></param>
        public void ReleasePool(string assetFullPath)
        {
            GameObjectPoolEntity poolEntity = null;
            if (!PoolEntityDic.TryGetValue(assetFullPath, out poolEntity))
                return;
            poolEntity.Release();
            PoolEntityDic.Remove(assetFullPath);
        }

        public void Dispose()
        {
            PoolEntityDic.Clear();
            PoolEntityDic = null;
        }
    }
}
